const express = require('express')
const router = express.Router()
const auth = require('../../middleware/auth')
const logger = require('../../utils/logger')
const AdStatisticsService = require('../../services/adStatisticsService')

/**
 * 检查管理员权限
 */
const checkAdminPermission = (req, res, next) => {
  if (req.user.role !== 'admin') {
    return res.status(403).json({
      success: false,
      code: 403,
      message: '权限不足'
    })
  }
  next()
}

/**
 * 获取广告概览统计
 */
router.get('/overview', auth, checkAdminPermission, async (req, res) => {
  try {
    const { startDate, endDate, platform, adType } = req.query
    
    const filters = {
      startDate,
      endDate,
      platform,
      adType
    }
    
    const overviewStats = await AdStatisticsService.getOverviewStats(filters)
    
    res.json({
      success: true,
      code: 200,
      data: overviewStats,
      message: '获取概览统计成功'
    })
  } catch (error) {
    logger.error('获取广告概览统计失败:', error)
    res.status(500).json({
      success: false,
      code: 500,
      message: '获取概览统计失败'
    })
  }
})

/**
 * 获取时间趋势数据
 */
router.get('/trend', auth, checkAdminPermission, async (req, res) => {
  try {
    const { startDate, endDate, platform, adType, groupBy = 'day' } = req.query
    
    const filters = {
      startDate,
      endDate,
      platform,
      adType,
      groupBy
    }
    
    const trendData = await AdStatisticsService.getTrendData(filters)
    
    res.json({
      success: true,
      code: 200,
      data: trendData,
      message: '获取趋势数据成功'
    })
  } catch (error) {
    logger.error('获取时间趋势数据失败:', error)
    res.status(500).json({
      success: false,
      code: 500,
      message: '获取趋势数据失败'
    })
  }
})

/**
 * 获取平台分布统计
 */
router.get('/platform', auth, checkAdminPermission, async (req, res) => {
  try {
    const { startDate, endDate, adType } = req.query
    
    const filters = {
      startDate,
      endDate,
      adType
    }
    
    const platformStats = await AdStatisticsService.getPlatformStats(filters)
    
    res.json({
      success: true,
      code: 200,
      data: platformStats,
      message: '获取平台统计成功'
    })
  } catch (error) {
    logger.error('获取平台分布统计失败:', error)
    res.status(500).json({
      success: false,
      code: 500,
      message: '获取平台统计失败'
    })
  }
})

/**
 * 获取广告类型统计
 */
router.get('/ad-type', auth, checkAdminPermission, async (req, res) => {
  try {
    const { startDate, endDate, platform } = req.query
    
    const filters = {
      startDate,
      endDate,
      platform
    }
    
    const adTypeStats = await AdStatisticsService.getAdTypeStats(filters)
    
    res.json({
      success: true,
      code: 200,
      data: adTypeStats,
      message: '获取广告类型统计成功'
    })
  } catch (error) {
    logger.error('获取广告类型统计失败:', error)
    res.status(500).json({
      success: false,
      code: 500,
      message: '获取广告类型统计失败'
    })
  }
})

/**
 * 获取收益分析
 */
router.get('/revenue', auth, checkAdminPermission, async (req, res) => {
  try {
    const { startDate, endDate, platform, adType } = req.query
    
    const filters = {
      startDate,
      endDate,
      platform,
      adType
    }
    
    const revenueAnalysis = await AdStatisticsService.getRevenueAnalysis(filters)
    
    res.json({
      success: true,
      code: 200,
      data: revenueAnalysis,
      message: '获取收益分析成功'
    })
  } catch (error) {
    logger.error('获取收益分析失败:', error)
    res.status(500).json({
      success: false,
      code: 500,
      message: '获取收益分析失败'
    })
  }
})

/**
 * 获取实时统计数据
 */
router.get('/realtime', auth, checkAdminPermission, async (req, res) => {
  try {
    const realTimeStats = await AdStatisticsService.getRealTimeStats()
    
    res.json({
      success: true,
      code: 200,
      data: realTimeStats,
      message: '获取实时统计成功'
    })
  } catch (error) {
    logger.error('获取实时统计数据失败:', error)
    res.status(500).json({
      success: false,
      code: 500,
      message: '获取实时统计失败'
    })
  }
})

/**
 * 生成统计报表
 */
router.post('/report', auth, checkAdminPermission, async (req, res) => {
  try {
    const {
      startDate,
      endDate,
      includeOverview = true,
      includeTrend = true,
      includePlatform = true,
      includeAdType = true,
      includeRevenue = true,
      format = 'json'
    } = req.body
    
    const options = {
      startDate,
      endDate,
      includeOverview,
      includeTrend,
      includePlatform,
      includeAdType,
      includeRevenue
    }
    
    const report = await AdStatisticsService.generateReport(options)
    
    if (format === 'json') {
      res.json({
        success: true,
        code: 200,
        data: report,
        message: '生成报表成功'
      })
    } else if (format === 'csv') {
      // 转换为CSV格式
      const csv = await convertReportToCSV(report)
      res.setHeader('Content-Type', 'text/csv')
      res.setHeader('Content-Disposition', `attachment; filename="ad_report_${Date.now()}.csv"`)
      res.send(csv)
    } else {
      res.status(400).json({
        success: false,
        code: 400,
        message: '不支持的报表格式'
      })
    }
  } catch (error) {
    logger.error('生成统计报表失败:', error)
    res.status(500).json({
      success: false,
      code: 500,
      message: '生成统计报表失败'
    })
  }
})

/**
 * 获取广告效果对比分析
 */
router.get('/comparison', auth, checkAdminPermission, async (req, res) => {
  try {
    const {
      startDate1,
      endDate1,
      startDate2,
      endDate2,
      platform,
      adType
    } = req.query
    
    if (!startDate1 || !endDate1 || !startDate2 || !endDate2) {
      return res.status(400).json({
        success: false,
        code: 400,
        message: '请提供两个时间段的开始和结束日期'
      })
    }
    
    const filters1 = { startDate: startDate1, endDate: endDate1, platform, adType }
    const filters2 = { startDate: startDate2, endDate: endDate2, platform, adType }
    
    const [period1Stats, period2Stats] = await Promise.all([
      AdStatisticsService.getOverviewStats(filters1),
      AdStatisticsService.getOverviewStats(filters2)
    ])
    
    // 计算变化率
    const comparison = {
      period1: {
        startDate: startDate1,
        endDate: endDate1,
        stats: period1Stats
      },
      period2: {
        startDate: startDate2,
        endDate: endDate2,
        stats: period2Stats
      },
      changes: {
        totalViews: calculateChangeRate(period1Stats.totalViews, period2Stats.totalViews),
        completedViews: calculateChangeRate(period1Stats.completedViews, period2Stats.completedViews),
        uniqueUsers: calculateChangeRate(period1Stats.uniqueUsers, period2Stats.uniqueUsers),
        totalRewards: calculateChangeRate(period1Stats.totalRewards, period2Stats.totalRewards),
        completionRate: calculateChangeRate(period1Stats.completionRate, period2Stats.completionRate),
        avgViewDuration: calculateChangeRate(period1Stats.avgViewDuration, period2Stats.avgViewDuration)
      }
    }
    
    res.json({
      success: true,
      code: 200,
      data: comparison,
      message: '获取对比分析成功'
    })
  } catch (error) {
    logger.error('获取广告效果对比分析失败:', error)
    res.status(500).json({
      success: false,
      code: 500,
      message: '获取对比分析失败'
    })
  }
})

/**
 * 清理统计缓存
 */
router.delete('/cache', auth, checkAdminPermission, async (req, res) => {
  try {
    await AdStatisticsService.clearExpiredCache()
    
    res.json({
      success: true,
      code: 200,
      message: '清理缓存成功'
    })
  } catch (error) {
    logger.error('清理统计缓存失败:', error)
    res.status(500).json({
      success: false,
      code: 500,
      message: '清理缓存失败'
    })
  }
})

/**
 * 计算变化率
 * @param {number} oldValue - 旧值
 * @param {number} newValue - 新值
 * @returns {Object} 变化率信息
 */
function calculateChangeRate(oldValue, newValue) {
  if (oldValue === 0) {
    return {
      absolute: newValue,
      percentage: newValue > 0 ? 100 : 0,
      trend: newValue > 0 ? 'up' : 'stable'
    }
  }
  
  const absolute = newValue - oldValue
  const percentage = (absolute / oldValue * 100).toFixed(2)
  const trend = absolute > 0 ? 'up' : absolute < 0 ? 'down' : 'stable'
  
  return {
    absolute: parseFloat(absolute.toFixed(2)),
    percentage: parseFloat(percentage),
    trend
  }
}

/**
 * 将报表转换为CSV格式
 * @param {Object} report - 报表数据
 * @returns {string} CSV字符串
 */
async function convertReportToCSV(report) {
  const lines = []
  
  // 添加报表头信息
  lines.push('广告统计报表')
  lines.push(`生成时间,${report.generatedAt}`)
  lines.push(`统计期间,${report.period.startDate} 至 ${report.period.endDate}`)
  lines.push('')
  
  // 概览统计
  if (report.data.overview) {
    const overview = report.data.overview
    lines.push('概览统计')
    lines.push('指标,数值')
    lines.push(`总观看次数,${overview.totalViews}`)
    lines.push(`完成观看次数,${overview.completedViews}`)
    lines.push(`独立用户数,${overview.uniqueUsers}`)
    lines.push(`总奖励积分,${overview.totalRewards}`)
    lines.push(`完成率,${overview.completionRate}%`)
    lines.push(`平均观看时长,${overview.avgViewDuration}秒`)
    lines.push('')
  }
  
  // 平台统计
  if (report.data.platform) {
    lines.push('平台统计')
    lines.push('平台,观看次数,完成次数,独立用户,总奖励,完成率,平均时长')
    report.data.platform.forEach(item => {
      lines.push(`${item.platform},${item.views},${item.completedViews},${item.uniqueUsers},${item.totalRewards},${item.completionRate}%,${item.avgDuration}秒`)
    })
    lines.push('')
  }
  
  // 广告类型统计
  if (report.data.adType) {
    lines.push('广告类型统计')
    lines.push('广告类型,观看次数,完成次数,独立用户,总奖励,完成率,平均时长')
    report.data.adType.forEach(item => {
      lines.push(`${item.adType},${item.views},${item.completedViews},${item.uniqueUsers},${item.totalRewards},${item.completionRate}%,${item.avgDuration}秒`)
    })
    lines.push('')
  }
  
  return lines.join('\n')
}

module.exports = router